package sjd.ahsj.springbootmybatisplusoracle.controller;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sjd.ahsj.springbootmybatisplusoracle.entity.BaseUser;
import sjd.ahsj.springbootmybatisplusoracle.entity.UserAmountBill;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.BaseContextHandler;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.IgnoreAuth;
import sjd.ahsj.springbootmybatisplusoracle.model.ReturnObject;
import sjd.ahsj.springbootmybatisplusoracle.service.IBaseUserService;
import sjd.ahsj.springbootmybatisplusoracle.service.IUserAmountBillService;
import sjd.ahsj.springbootmybatisplusoracle.util.AlipayCore;
import sjd.ahsj.springbootmybatisplusoracle.util.DateUtil;
import sjd.ahsj.springbootmybatisplusoracle.util.HttpClientUtil;
import sjd.ahsj.springbootmybatisplusoracle.util.MD5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * <p>
 * 动漫 前端控制器
 * </p>
 *
 * @author zhanghaogao
 * @since 2018-09-18
 */
@Api(description = "支付")
@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private IUserAmountBillService iUserAmountBillService;
    @Autowired
    private IBaseUserService iBaseUserService;


    @Value("${abc_pid}")
    private String abcPid;
    @Value("${abc_key}")
    private String abcKey;
    @Value("${ahc_notify_url}")
    private String ahcNotifyUrl;

    @Value("${hh_pid}")
    private String hhPid;
    @Value("${hh_key}")
    private String hhKey;
    @Value("${hh_notify_url}")
    private String hhNotifyUrl;

    @Value("${ya_pid}")
    private String yaPid;
    @Value("${ya_key}")
    private String yaKey;
    @Value("${ya_notify_url}")
    private String yaNotifyUrl;

    @Value("${hx_pid}")
    private String hxPid;
    @Value("${hx_key}")
    private String hxKey;
    @Value("${hx_notify_url}")
    private String hxNotifyUrl;

    @ApiOperation("ABC云支付")
    @RequestMapping(value = "/abcPay", method = RequestMethod.POST)
    public ReturnObject<String> abcPay(@ApiParam("充值类型（0：69，1：99,2:49:3:日卡，4：月卡，5：季卡）") Long type,
                                       @ApiParam("alipay:支付宝,tenpay:财付通,qqpay:QQ钱包,wxpay:微信支付") String abcType,
                                       @ApiParam("支付回调页面地址") String url,
                                       @ApiParam("支付平台（0：abc，1：好好，2：优爱,3:彗星）") Long terrace) throws UnsupportedEncodingException {
        String name;
        UserAmountBill userAmountBill;
        BaseUser baseUser = iBaseUserService.selectById(BaseContextHandler.getUserID());
        if (type == 0) {
            name = "充值69元获取8800金币";
            userAmountBill = new UserAmountBill(BaseContextHandler.getUserID(), 69L, 8800L, 0, null, null, 0, null);
        } else if (type == 1) {
            name = "充值99元获取13800金币";
            userAmountBill = new UserAmountBill(BaseContextHandler.getUserID(), 99L, 13800L, 0, null, null, 0, null);
        } else if (type == 2) {
            name = "充值49元获取4900金币";
            userAmountBill = new UserAmountBill(BaseContextHandler.getUserID(), 49L, 4900L, 0, null, null, 0, null);
        } else if (type == 3) {
            name = "充值日卡";
            userAmountBill = new UserAmountBill(BaseContextHandler.getUserID(), 39L, 0L, 1,
                    baseUser.getMemberEndTime() != null ? baseUser.getMemberEndTime() : new Date(),
                    DateUtil.getSomeDay(baseUser.getMemberEndTime() != null ? baseUser.getMemberEndTime() :
                            new Date(), 1), 0, null);
        } else if (type == 4) {
            name = "充值月卡";
            userAmountBill = new UserAmountBill(BaseContextHandler.getUserID(), 119L, 0L, 1,
                    baseUser.getMemberEndTime() != null ? baseUser.getMemberEndTime() : new Date(),
                    DateUtil.getSomeDay(baseUser.getMemberEndTime() != null ? baseUser.getMemberEndTime() :
                            new Date(), 30), 0, null);
        } else {
            name = "充值季卡";
            userAmountBill = new UserAmountBill(BaseContextHandler.getUserID(), 199L, 0L, 1,
                    baseUser.getMemberEndTime() != null ? baseUser.getMemberEndTime() : new Date(),
                    DateUtil.getSomeDay(baseUser.getMemberEndTime() != null ? baseUser.getMemberEndTime() :
                            new Date(), 90), 0, null);
        }
        iUserAmountBillService.insert(userAmountBill);
        String key;
        String pid;
        String notifyUrl;
        if (terrace == 0) {
            key = abcKey;
            pid = abcPid;
            notifyUrl = ahcNotifyUrl;
        } else if (terrace == 1) {
            key = hhKey;
            pid = hhPid;
            notifyUrl = hhNotifyUrl;
        } else if (terrace == 2) {
            key = yaKey;
            pid = yaPid;
            notifyUrl = yaNotifyUrl;
        } else {
            key = hxKey;
            pid = hxPid;
            notifyUrl = hxNotifyUrl;
        }
//        String[] parameters = {
//                "pid=" + pid + "",
//                "type=" + abcType + "",
//                "out_trade_no=" + userAmountBill.getId() + "",
//                "notify_url=" + notifyUrl + "",
//                "return_url=" + url + "",
//                "name=" + name + "",
//                "money=" + userAmountBill.getAmount() + "",
//
//
//        };
        SortedMap<String, String> map = new TreeMap<String, String>();
//        map.put("pid", pid);
        map.put("merchant_id", pid);
        map.put("total_fee", userAmountBill.getAmount().toString());
        map.put("out_trade_no", userAmountBill.getId().toString());
        map.put("notify_url", notifyUrl);
        map.put("return_url", url);
        map.put("format", "json");

        map.put("sign", md5("merchant_id=" + pid + "&total_fee=" + userAmountBill.getAmount().toString() +
                "&out_trade_no=" + userAmountBill.getId().toString() + "&notify_url=" + notifyUrl + "&return_url=" + url + "&" + key));
        map.put("pay_type", "wechat.h5");
//        map.put("money","0.01");
//        map.put("sitename", "comic");
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        String post = httpClientUtil.doPost("https://www.531368.com/api/unified_order", map, "utf-8");

        return new ReturnObject<>(0, "", JSONObject.parseObject(post).getJSONObject("data").get("url").toString());
    }


    @IgnoreAuth
    @ApiOperation("ABC云支付回调")
    @RequestMapping(value = "/abcPayNotify")
    public ReturnObject<String> abcPayNotify(@ApiParam("商户ID") Integer pid,
                                             @ApiParam("易支付订单号") String trade_no,
                                             @ApiParam("商户订单号") String out_trade_no,
                                             @ApiParam("支付方式") String type,
                                             @ApiParam("商品名称") String name,
                                             @ApiParam("商品金额") String money,
                                             @ApiParam("支付状态") String trade_status,
                                             @ApiParam("签名字符串") String sign,
                                             @ApiParam("签名类型") String sign_type) {
        UserAmountBill userAmountBill = iUserAmountBillService.selectById(out_trade_no);
        if (userAmountBill != null && userAmountBill.getPayStatus() == 0) {
            userAmountBill.setPayStatus(1);
            if (userAmountBill.getType() == 0) {
                iBaseUserService.addAmount(userAmountBill.getUserId(), userAmountBill.getGold());

            } else {
                BaseUser baseUser = new BaseUser();
                baseUser.setMemberEndTime(userAmountBill.getEndTime());
                baseUser.setId(userAmountBill.getUserId());
                iBaseUserService.updateById(baseUser);
            }
            iUserAmountBillService.updateById(userAmountBill);
        }
        return new ReturnObject<>(0, "回调成功");
    }

    /**
     * 支付宝签名
     *
     * @return
     */
    private String signAllString(String key, SortedMap<String, String> map) {
        //除去数组中的空值和签名参数
        Map<String, String> sPara = AlipayCore.paraFilter(map);
        String prestr = AlipayCore.createLinkString(sPara);
        String mysign = MD5.sign(prestr, key, "utf-8");
        prestr = prestr + "&sign=" + mysign + "&pay_type=wechat.h5";
        return prestr;
    }


    private String md5(String value) {
        String result = null;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update((value).getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException error) {
            error.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte b[] = md5.digest();
        int i;
        StringBuffer buf = new StringBuffer("");

        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }

        result = buf.toString();
        return result;
    }

}

